package com.xyzh05.webapp.action;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.model.Attachment;
import com.xyzh05.service.AttachmentManager;

public class AttachmentAction extends UploadFileAction implements Preparable {

	private static final long serialVersionUID = -12312312312111L;
	private AttachmentManager attachmentManager;
	private List<Attachment> attachments;
	private Attachment attachment;
	private Long id;
	private Long type;
	private String query;
	private String msg;
	private String inputPath;
	private String fileName;

	public void setAttachmentManager(AttachmentManager attachmentManager) {
		this.attachmentManager = attachmentManager;
	}

	public List<Attachment> getAttachments() {
		return attachments;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public AttachmentManager getAttachmentManager() {
		return attachmentManager;
	}

	public void setAttachments(List<Attachment> attachments) {
		this.attachments = attachments;
	}

	/**
	 * Grab the entity from the database before populating with request
	 * parameters
	 */
	public void prepare() {
		if (getRequest().getMethod().equalsIgnoreCase("post")) {
			// prevent failures on new
			String attachmentId = getRequest().getParameter("attachment.id");
			if (attachmentId != null && !attachmentId.equals("")) {
				attachment = attachmentManager.get(new Long(attachmentId));
			}
		}
	}

	public String initUploadAttachment() {
		return "initUploadAttachment";
	}

	public String uploadAttachment() {
		try {
			// 获取上传文件名字
			String[] fileNames = this.getUploadFileName();
			// 设置保存路径
			setSavePath("/uploadfile");
			// 上传文件
			uploadFiles();
			attachment.setName(uploadFileName[0]);
			attachment.setPath(targetPath[0]);
			attachment.setSize(Long.valueOf(fileSize[0]));
			attachment.setUploadTime(new Date());
			attachment.setUploadUser(getCurrentUser().getId());
			attachment.setType(uploadContentType[0]);
			attachment.setOwnerId(id);
			attachment.setOwnerType(type);
			attachmentManager.save(attachment);
			attachmentManager.save(attachment);
			msg = "上传成功！";
		} catch (Exception e) {
			log.error("上传附件失败!", e);
			return "error";
		}
		return "uploadAttachment";
	}

	public void setQ(String q) {
		this.query = q;
	}

	public String list() {
		attachments = attachmentManager.search(query, Attachment.class);
		return SUCCESS;
	}

	public String delete() {
		attachmentManager.remove(attachment.getId());
		saveMessage(getText("attachment.deleted"));

		return SUCCESS;
	}

	public String edit() {
		if (id != null) {
			attachment = attachmentManager.get(id);
		} else {
			attachment = new Attachment();
		}

		return SUCCESS;
	}

	public String save() throws Exception {
		if (cancel != null) {
			return "cancel";
		}

		if (delete != null) {
			return delete();
		}

		boolean isNew = (attachment.getId() == null);

		attachmentManager.save(attachment);

		String key = (isNew) ? "attachment.added" : "attachment.updated";
		saveMessage(getText(key));

		if (!isNew) {
			return INPUT;
		} else {
			return SUCCESS;
		}
	}

	/**
	 * 下载文件
	 * @return
	 * @throws Exception
	 */                  
	public InputStream getInputStream() throws Exception {
		InputStream in = null;
		try {
			attachments = attachmentManager.findAttachments(id, type);
			attachment = attachments.get(0);			
			in = new BufferedInputStream(new FileInputStream(attachment.getPath()), BUFFER_SIZE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return in;
	}
	
	/**
	 * 如果下载文件名为中文,进行字符编码转换
	 * @return
	 */
	public String getDownloadChineseFileName() {   
		attachments = attachmentManager.findAttachments(id, type);	
		attachment = attachments.get(0);		
        String downloadChineseFileName = attachment.getName();  
        try {   
        	downloadChineseFileName = new String(downloadChineseFileName.getBytes(), "ISO8859-1");   
        } catch (UnsupportedEncodingException e) {   
            e.printStackTrace();   
        }   
        return downloadChineseFileName;   
    }   


	public void setId(Long id) {
		this.id = id;
	}

	public Attachment getAttachment() {
		return attachment;
	}

	public void setAttachment(Attachment attachment) {
		this.attachment = attachment;
	}

	public Long getType() {
		return type;
	}

	public void setType(Long type) {
		this.type = type;
	}

	public Long getId() {
		return id;
	}

	public String getInputPath() {
		return inputPath;
	}

	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

}